from expression import expression
from expression import environment
import sys
sys.path.append(sys.path[0] + "/../LLVM")
from llvmhelper import llvmHelper
from llvm import *
from commonRoutines import commonRoutines

class varBinding:
	def __init__(self, name, value, exp):
		self.name = name
		self.value = value
		self.exp = exp
		self.eframe = None
	def evaluate(self, env):
		newEnv = environment(self.name, self.value.evaluate(env), env)
		#print "varbind env: \n", str(newEnv)
		self.exp.evaluate(newEnv)
 
	def __str__(self):
		return "varBinding( " + str(self.name) + ", " + str(self.value) + ",\n" + str(self.exp) + ")"

	def traverse(self, helper):
		#print "Taversing Var binding: " + self.name 
		#print "Adding var: " + self.name + " to Scope "+ str(helper.scopecount)
		helper.addVarToScope(self.name)
		#helper.displayScope()
		scope = helper.getCurrentScope()
		var = scope.get(self.name)
		#print var + " name: " + self.name
		self.eframe = var
		self.value.traverse(helper)
		if(self.exp != None):
			#print "\nTraversing "+ str(self.exp) + "\n"
			self.exp.traverse(helper)
		
	def toLLVM(self, helper):
		helper.descend("varBinding")
		
		self.value.toLLVM(helper)
		c = commonRoutines(helper)
		
		expValue = helper.getReturns()[0]
		#sys.stderr.write("self.eframe: " + str(self.eframe))
		c.setVar(self.eframe[1], self.eframe[2], expValue)
		
		if(self.exp != None):
			self.exp.toLLVM(helper)
			helper.ascend(helper.getReturns()[1]) #what do I do here?
		else:
			helper.ascend(helper.getReturns()[0]) #what do I do here?
		helper.setLabel(helper.getLastLabel())
		#sys.stderr.write("\nvarBinding Returns: " + str(helper.getReturns()))
		
		
